package com.imooc.controller;

import com.imooc.BO.ShopCartBO;
import com.imooc.constant.RedisConstant;
import com.imooc.service.ItemsService;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import com.imooc.utils.RedisOperator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author gcq
 * @Create 2022-01-08
 */
@Api(value = "购物车接口Controller", tags = {"购物车接口相关API"})
@RestController
@RequestMapping("shopcart")
public class ShopCartController extends BaseController {

    @Autowired
    private ItemsService itemsService;

    @Autowired
    private RedisOperator redisOperator;

    @ApiOperation(value = "添加商品到购物车", notes = "添加商品到购物车", httpMethod = "POST")
    @PostMapping("/add")
    public IMOOCJSONResult info(@ApiParam(name = "userId", value = "用户Id", required = true)
                                @RequestParam String userId,
                                @RequestBody ShopCartBO shopCartBO,
                                HttpServletRequest request,
                                HttpServletResponse response) {
        if (StringUtils.isBlank(userId)) {
            return IMOOCJSONResult.errorMsg("");
        }

        System.out.println(shopCartBO.toString());
        // TODO 前端用户在登录的情况下，添加商品到购物车中，会同时在后端同步购物车到redis缓存

        // key userId value List<ShopCartBo>
        // 需要判断当前购物车中已经存在的商品，如果存在累加购买数量
        String shopCartJson = redisOperator.get(RedisConstant.FOODIE_SHOP_CART + userId);
        List<ShopCartBO> shopCartList = null;
        if (StringUtils.isNotEmpty(shopCartJson)) {
            // redis 中有购物车了
            shopCartList = JsonUtils.jsonToList(shopCartJson, ShopCartBO.class);

            // 判断购物车中是否还有商品，如果有的话counts累加
            boolean isHaving = false;
            for (ShopCartBO sc : shopCartList) {
                String tmpSpecId = sc.getSpecId();
                if (tmpSpecId.equals(shopCartBO.getSpecId())) { // 规格匹配的话，就是购物车中存在这个商品
                    // 当前已有购买数量 + 新增加的购买数量
                    sc.setBuyCounts(sc.getBuyCounts() + shopCartBO.getBuyCounts());
                    isHaving = true;
                }
            }

            // 购物车中没有这个商品，则将当前商品添加进购物车中
            if (!isHaving) {
                shopCartList.add(shopCartBO);
            }
        } else {
            // redis中没有购物车
            shopCartList = new ArrayList<>();
            // 将当前商品添加进购物车
            shopCartList.add(shopCartBO);
        }

        // 覆盖现有的 redis 中的购物车
        redisOperator.set(RedisConstant.FOODIE_SHOP_CART + userId, JsonUtils.objectToJson(shopCartList));

        return IMOOCJSONResult.ok();
    }

    @ApiOperation(value = "从购物车中删除商品", notes = "从购物车中删除商品", httpMethod = "POST")
    @PostMapping("/del")
    public IMOOCJSONResult del(@ApiParam(name = "userId", value = "用户Id", required = true)
                               @RequestParam String userId,
                               @ApiParam(name = "itemSpecId", value = "商品规格Id", required = true)
                               @RequestParam String itemSpecId,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(itemSpecId)) {
            return IMOOCJSONResult.errorMsg("参数不能为空");
        }

        // TODO 用户在页面删除购物车中的商品数据，如果此时已登录，则需要同步删除后端购物车中数据
        String shopCartJson = redisOperator.get(RedisConstant.FOODIE_SHOP_CART + userId);
        if(StringUtils.isNotBlank(shopCartJson)) {
            // redis 中有购物车
            List<ShopCartBO> shopCartList = JsonUtils.jsonToList(shopCartJson, ShopCartBO.class);
            // 判断购物车中是否存在商品，存在则删除
            for (ShopCartBO sc : shopCartList) {
                String tmpSpecId = sc.getSpecId();
                if(tmpSpecId.equals(itemSpecId)) {
                    shopCartList.remove(sc);
                    break;
                }
            }
            // 覆盖现有 redis 中得购物车
            redisOperator.set(RedisConstant.FOODIE_SHOP_CART + userId, JsonUtils.objectToJson(shopCartList));
        }
        return IMOOCJSONResult.ok();
    }
}